<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="礼簿名称" prop="bookId">
        <el-select v-model="queryParams.bookId" placeholder="礼簿名称" clearable style="width: 220px">
          <el-option
              v-for="dict in bookList"
              :key="dict.bookId"
              :label="dict.bookName"
              :value="dict.bookId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="宾客姓名" prop="giverName">
        <el-input
            v-model="queryParams.giverName"
            placeholder="请输入送礼人姓名"
            clearable
            @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="宾客关系" prop="relationship">
        <el-select v-model="queryParams.relationship" placeholder="亲友关系" clearable style="width: 240px">
          <el-option
              v-for="dict in gift_relation_ship"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="收款方式" prop="giftType">
        <el-select v-model="queryParams.giftType" placeholder="收款方式" clearable style="width: 240px">
          <el-option
              v-for="dict in gift_channel_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="收款金额" prop="amount">
        <el-input
            v-model="queryParams.amount"
            placeholder="请输入金额"
            clearable
            @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="收款日期" prop="giftDate">
        <el-date-picker clearable
                        v-model="queryParams.giftDate"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="请选择日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
        >删除</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="recordsList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" >
        <template #default="scope">
          <!-- 计算序号：(当前页-1)*每页条数 + 索引 + 1 -->
          {{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column label="礼簿名称"
                       align="center"
                       prop="bookId"
                        :formatter="formatBookName">

      </el-table-column>
      <el-table-column label="礼金序号"
                       align="center"
                       prop="bookSeq"
                       />

      <el-table-column label="宾客姓名" align="center" prop="giverName" />
      <el-table-column label="宾客关系" align="center" prop="relationship" >
        <template #default="scope">
          <dict-tag :options="gift_relation_ship" :value="scope.row.relationship" />
        </template>
      </el-table-column>
      <el-table-column label="收款方式" align="center" prop="giftType" >
        <template #default="scope">
          <dict-tag :options="gift_channel_type" :value="scope.row.giftType" />
        </template>
      </el-table-column>
      <el-table-column label="收款金额(元)" align="center" prop="amount" />
      <el-table-column label="收款日期" align="center" prop="giftDate" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.giftDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="150" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"  >修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改参数配置对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="configRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="礼簿名称" prop="bookId">
          <el-select v-model="form.bookId" placeholder="礼簿名称">
            <el-option
                v-for="dict in modelBookList"
                :key="dict.bookId"
                :label="dict.bookName"
                :value="dict.bookId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="宾客姓名" prop="giverName">
          <el-input v-model="form.giverName" placeholder="请输入送礼人姓名" />
        </el-form-item>
        <el-form-item label="宾客关系" prop="relationship">
          <el-radio-group v-model="form.relationship">
            <el-radio
                v-for="dict in gift_relation_ship"
                :key="dict.value"
                :value="dict.value"
            >{{ dict.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="收款方式" prop="relationship">
          <el-radio-group v-model="form.giftType">
            <el-radio
                v-for="dict in gift_channel_type"
                :key="dict.value"
                :value="dict.value"
            >{{ dict.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="收款金额" prop="amount">
          <el-radio-group v-model="form.amount" @change="handleAmountChange">
            <el-radio
                v-for="dict in gift_amount_value"
                :key="dict.value"
                :value="dict.value"
            >{{ dict.label }}</el-radio>
            <el-radio :value="'other'">其他</el-radio>
          </el-radio-group>
          <el-input
              v-if="form.amount === 'other'"
              v-model="form.otherAmount"
              type="number"
              placeholder="请输入金额"
              style="margin-top: 10px; width: 200px"
              min="0"
              step="1"
          ></el-input>
        </el-form-item>
        <el-form-item label="收款日期" prop="giftDate">
          <el-date-picker clearable
                          v-model="form.giftDate"
                          type="date"
                          value-format="YYYY-MM-DD"
                          placeholder="请选择日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Config">
import { listRecords, getRecords, delRecords, addRecords, updateRecords, allBooks } from "@/api/book/records.js"
const { proxy } = getCurrentInstance()
const { gift_relation_ship } = proxy.useDict("gift_relation_ship")
const { gift_channel_type } = proxy.useDict("gift_channel_type")
const { gift_amount_value } = proxy.useDict("gift_amount_value")

const recordsList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const dateRange = ref([])
const bookList = ref([])

const modelBookList = ref([])

allBooks().then(response => {
  let resultData = response.data;
  resultData.forEach(v=>{
    v.value = v.bookId;
    v.label = v.bookName;
  })
  bookList.value = resultData
})

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    bookId: null,
    giverName: null,
    relationship: null,
    giftType: null,
    amount: null,
    giftDesc: null,
    giftDate: null,
  },
  rules: {
    bookId: [
      { required: true, message: "关联礼簿ID不能为空", trigger: "blur" }
    ],
    giverName: [
      { required: true, message: "送礼人姓名不能为空", trigger: "blur" }
    ],
    relationship: [
      { required: true, message: "与主人关系不能为空", trigger: "change" }
    ],
    giftType: [
      { required: true, message: "礼金类型不能为空", trigger: "change" }
    ],
    giftDate: [
      { required: true, message: "送礼日期不能为空", trigger: "blur" }
    ],
    amount: [
      { required: true, message: "金额不能为空", trigger: "change" }
    ],
  }
})

const { queryParams, form, rules } = toRefs(data)


function formatBookName(row, column, cellValue) {
  const statusItem  = bookList.value.find(v => v.bookId === cellValue)
  return statusItem ? statusItem.bookName : cellValue;
}

/** 查询参数列表 */
function getList() {
  loading.value = true
  listRecords(proxy.addDateRange(queryParams.value, dateRange.value)).then(response => {
    recordsList.value = response.rows
    total.value = response.total
    loading.value = false
  }).then(()=>{
    loading.value = false
  }).catch((err)=>{
    loading.value = false
  })
}

/** 取消按钮 */
function cancel() {
  open.value = false
  reset()
}

/** 表单重置 */
function reset() {
  form.value = {
    recordsId: undefined,
    bookId: undefined,
    giftDate: undefined,
    relationship: undefined,
    giftType: undefined,
    amount: undefined,
    remark: undefined
  }
  proxy.resetForm("configRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  dateRange.value = []
  proxy.resetForm("queryRef")
  handleQuery()
}

/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.recordsId)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加记录"
  modelBookList.value = bookList.value
  let find = modelBookList.value.find(v=>v.bookDefault === 'Y');
  if (find) {
    form.value = {
      bookId: find.bookId,
    }
  }
  form.value.giftDate = formatDate(new Date())
  form.value.relationship = gift_relation_ship.value[0].value
  form.value.giftType = gift_channel_type.value[0].value
  form.value.amount = gift_amount_value.value[0].value

}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  modelBookList.value = bookList.value
  const configId = row.recordsId || ids.value
  getRecords(configId).then(response => {
    form.value = response.data
    let find = gift_amount_value.value.find(v=>Number(v.value) === form.value.amount);
    if (!find) {
      form.value.otherAmount = form.value.amount
      form.value.amount = 'other'
    } else {
      form.value.amount = find.value
    }
    open.value = true;
    title.value = "修改参数"
  })
}

/** 提交按钮 */
function submitForm() {

  proxy.$refs["configRef"].validate(valid => {
    if (form.value.amount === 'other') {
      if (!form.value.otherAmount || form.value.otherAmount === '') {
        proxy.$modal.msgError("请输入礼金");
        return
      }
      form.value.amount = form.value.otherAmount
    }
    if (valid) {
      if (form.value.recordsId !== undefined) {
        updateRecords(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addRecords(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const configIds = row.recordsId || ids.value
  proxy.$modal.confirm('是否确认删除参数编号为"' + configIds + '"的数据项？').then(function () {
    return delRecords(configIds)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

function formatDate(date) {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
}

function handleAmountChange(value) {
  if (value !== 'other') {
    form.value.otherAmount = ''
  }
}

getList()
</script>
